<template>
  <div class="app-container">
    <div v-loading="loading">
      <!-- 帖子详情 -->
      <div class="post-details" v-if="post">
        <h1 class="post-title">{{ post.title }}</h1>
        <div class="post-meta">
          <span>发布用户：{{ post.userName }}</span>
          <span style="margin-left: 20px"
            >发布时间：{{ post.createTime | dateTimeFormat }}</span
          >
        </div>
        <div class="post-content">{{ post.content }}</div>
      </div>

      <!-- 回复列表 -->
      <div class="reply-section" v-if="post">
        <h3>回复列表</h3>
        <div class="reply-list">
          <el-table
            v-loading="replyLoading"
            :data="replyList"
            border
            fit
            highlight-current-row
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="180" />
            <el-table-column prop="content" label="回复内容" />
            <el-table-column prop="userName" label="回复用户" width="120" />
            <el-table-column prop="createTime" label="回复时间" width="180">
              <template slot-scope="{ row }">
                {{ row.createTime | dateTimeFormat }}
              </template>
            </el-table-column>
            <el-table-column width="120" label="操作" align="center">
              <template slot-scope="{ row }">
                <el-button size="mini" type="danger" @click="deleteReply(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="replyTotal > 0"
            :total="replyTotal"
            :page.sync="replyQueryParam.pageIndex"
            :limit.sync="replyQueryParam.pageSize"
            @pagination="getReplyList"
          />
        </div>

        <!-- 发表回复 -->
        <div class="add-reply">
          <h3>发表回复</h3>
          <el-form :model="replyForm" ref="replyForm" :rules="replyRules">
            <el-form-item prop="content">
              <el-input
                type="textarea"
                :rows="4"
                placeholder="请输入回复内容"
                v-model="replyForm.content"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitReply"
                :loading="replySubmitLoading"
                >提交回复</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import forumApi from "@/api/forum";
import Pagination from "@/components/Pagination";

export default {
  components: { Pagination },
  filters: {
    dateTimeFormat(time) {
      if (time) {
        const date = new Date(time);
        return (
          date.getFullYear() +
          "-" +
          String(date.getMonth() + 1).padStart(2, "0") +
          "-" +
          String(date.getDate()).padStart(2, "0") +
          " " +
          String(date.getHours()).padStart(2, "0") +
          ":" +
          String(date.getMinutes()).padStart(2, "0")
        );
      }
      return "";
    },
  },
  data() {
    return {
      loading: false,
      postId: "",
      post: null,

      // 回复相关
      replyLoading: false,
      replyList: [],
      replyTotal: 0,
      replyQueryParam: {
        postId: "",
        pageIndex: 1,
        pageSize: 10,
      },

      // 添加回复表单
      replyForm: {
        content: "",
        postId: "",
      },
      replyRules: {
        content: [
          { required: true, message: "请输入回复内容", trigger: "blur" },
          {
            min: 2,
            max: 500,
            message: "回复内容长度在 2 到 500 个字符",
            trigger: "blur",
          },
        ],
      },
      replySubmitLoading: false,
    };
  },
  created() {
    this.postId = this.$route.query.id;
    if (this.postId) {
      this.loadPostDetails();
      this.replyQueryParam.postId = this.postId;
      this.replyForm.postId = this.postId;
      this.getReplyList();
    } else {
      this.$message.error("参数错误");
      this.$router.push("/forum/post/list");
    }
  },
  methods: {
    // 加载帖子详情
    loadPostDetails() {
      this.loading = true;
      // 创建一个查询对象，包含帖子ID
      const query = {
        pageIndex: 1,
        pageSize: 1,
        // 这里假设后端支持按ID查询，如果不支持，需要调整后端或前端逻辑
        id: this.postId,
      };

      forumApi
        .getPostPage(query)
        .then((data) => {
          const re = data.response;
          if (re.list && re.list.length > 0) {
            this.post = re.list[0];
          } else {
            this.$message.error("帖子不存在或已被删除");
            this.$router.push("/forum/post/list");
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.$message.error("获取帖子详情失败");
        });
    },

    // 获取回复列表
    getReplyList() {
      this.replyLoading = true;
      forumApi
        .getReplyPage(this.replyQueryParam)
        .then((data) => {
          const re = data.response;
          this.replyList = re.list;
          this.replyTotal = re.total;
          this.replyQueryParam.pageIndex = re.pageNum;
          this.replyLoading = false;
        })
        .catch(() => {
          this.replyLoading = false;
          this.$message.error("获取回复列表失败");
        });
    },

    // 删除回复
    deleteReply(row) {
      this.$confirm("确认删除该回复?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          forumApi.deleteReply(row.id).then((re) => {
            if (re.code === 1) {
              this.getReplyList();
              this.$message.success("删除成功");
            } else {
              this.$message.error(re.message || "删除失败");
            }
          });
        })
        .catch(() => {});
    },

    // 提交回复
    submitReply() {
      this.$refs.replyForm.validate((valid) => {
        if (valid) {
          this.replySubmitLoading = true;
          forumApi
            .createReply(this.replyForm)
            .then((data) => {
              if (data.code === 1) {
                this.$message.success("回复成功");
                this.replyForm.content = "";
                this.getReplyList();
              } else {
                this.$message.error(data.message || "回复失败");
              }
              this.replySubmitLoading = false;
            })
            .catch(() => {
              this.replySubmitLoading = false;
            });
        }
      });
    },
  },
};
</script>

<style scoped>
.post-details {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.post-title {
  font-size: 24px;
  margin-bottom: 15px;
}

.post-meta {
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.post-content {
  font-size: 16px;
  line-height: 1.8;
  white-space: pre-wrap;
}

.reply-section {
  margin-top: 20px;
}

.reply-list {
  margin-bottom: 30px;
}

.add-reply {
  margin-top: 20px;
}
</style>
